package com.xiaoniu.douyinvideo.page

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.text.TextUtils
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.PathUtils
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.xiaoniu.douyinvideo.apps.VideoApp
import com.xiaoniu.douyinvideo.databinding.ActivityMainBinding
import com.xiaoniu.douyinvideo.util.LogUtil
import com.xiaoniu.douyinvideo.util.LogUtil.i
import com.xiaoniu.douyinvideo.util.PUtil
import com.xiaoniu.douyinvideo.util.VideoAppUtil.isSupportApp
import com.xiaoniu.douyinvideo.util.toast
import com.xiaoniu.douyinvideo.view.KWebView.HtmlCallback
import java.io.File

/**
 * @author zhaohe
 */
class MainActivity : AppCompatActivity() {
    private var binding: ActivityMainBinding? = null

    private var videoApp: VideoApp? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding!!.getRoot())

        binding!!.webView.setHtmlCallback(object : HtmlCallback {
            override fun videoUrl(urls: Pair<String, String>?) {
                parserVideoUrl(urls)
            }
        })
        binding!!.tvUrl.setOnLongClickListener { v: View? ->
            copyTpClip(binding!!.tvUrl.getText().toString())
            false
        }

        ViewCompat.setOnApplyWindowInsetsListener(binding!!.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(0, systemBars.top, 0, 0)
            insets
        }

        checkPermission()

        val hasShowedTip = PUtil.getPreferences(PUtil.KEY_SHOWED_TIP, false)
        binding?.nsvTip?.visibility = if (hasShowedTip == true) View.GONE else View.VISIBLE
    }

    /**
     * 检查权限
     */
    @SuppressLint("CheckResult")
    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) return
        XXPermissions.with(this)
            // 申请多个权限
            .permission(PermissionLists.getWriteExternalStoragePermission())
            //.unchecked()
            .request { grantedList, deniedList ->
                val allGranted = deniedList.isEmpty()
                if (allGranted) {
                    i("有存储权限")
                } else {
                    "请打开存储权限".toast()
                }
            }
    }

    /**
     * 复制数据
     *
     * @param data
     */
    private fun copyTpClip(data: String?) {
        if (TextUtils.isEmpty(data)) {
            return
        }
        val manager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val mClipData = ClipData.newPlainText("Label", data)
        manager.setPrimaryClip(mClipData)
        videoApp!!.showToast("复制成功")
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus) {
            return
        }
        // 在 Android Q（10）中，应用在前台的时候才可以获取到剪切板内容。
        val tempClipText = this.clipboardContent

        LogUtil.i("粘贴板数据：tempClipText = $tempClipText")
        if (TextUtils.isEmpty(tempClipText)) {
            return
        }
        val tempVideoApp = isSupportApp(tempClipText)
        if (videoApp != null && TextUtils.equals(videoApp!!.htmlUrl(), tempVideoApp!!.htmlUrl())) {
            return
        }
        videoApp = tempVideoApp
        binding!!.tvUrl.setText("")
        if (videoApp != null) {
            binding!!.tvClipInfo.setText(tempClipText)
        }
    }


    val clipboardContent: String?
        /**
         * 获取剪切板内容
         *
         * @return
         */
        get() {
            val cm =
                getSystemService(CLIPBOARD_SERVICE) as ClipboardManager?
            if (cm == null) {
                return null
            }
            val data = cm.getPrimaryClip()
            if (data == null) {
                return null
            }
            val item = data.getItemAt(0)
            if (item == null) {
                return null
            }
            return item.getText().toString()
        }

    /**
     * 点击解析按钮
     *
     * @param view
     */
    fun startParse(view: View?) {
        i("点击开始解析按钮")
        if (videoApp == null) {
            return
        }
        binding!!.btnParse.setEnabled(false)
        i("clip_url = " + videoApp!!.htmlUrl())
        binding!!.webView.setVideoApp(videoApp!!)
    }

    /**
     * 解析视频url
     *
     * @param finalVideoUrl
     */
    private fun parserVideoUrl(videoUrlPair: Pair<String, String>?) {
        if (videoUrlPair == null) return
        val htmlVideoUrl = videoUrlPair.first
        val finalVideoUrl = videoUrlPair.second
        i("html videoUrl = $htmlVideoUrl")
        i("final videoUrl = $finalVideoUrl")
        if (TextUtils.isEmpty(finalVideoUrl)) {
            return
        }
        runOnUiThread {
            binding!!.tvUrl.text = htmlVideoUrl
            binding!!.btnParse.setEnabled(true)
        }

        val internalMoviesPath = PathUtils.getExternalAppDownloadPath() + File.separator + EncryptUtils.encryptMD5ToString(htmlVideoUrl) + ".mp4"

        i("跳到视频播放页进行下载:$internalMoviesPath")
        val intent = Intent(this, VideoActivity::class.java)
        intent.putExtra("download_url", internalMoviesPath)
        intent.putExtra("video_url", finalVideoUrl)
        startActivity(intent)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
        Process.killProcess(Process.myPid())
    }


    fun closeTip(view: View?){
        binding!!.nsvTip.visibility = View.GONE
        PUtil.putPreferences(PUtil.KEY_SHOWED_TIP, true)
    }
}